using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Ajax;
using DomainModel.Entities;
using System.Web.Routing;
using System.Web.Security;
using DomainModel.Concrete;
using WebCore.Caching;
using WebCore;
using WebCore.Helpers;

namespace WebController.Controllers
{
    public class _baseController : Controller
    {
        /// <summary>
        /// Contains User state information retrieved from the authentication system
        /// </summary>
        ///

        string openID = string.Empty;

        protected User _user = new User();
        UsersRepository usersRepository = new UsersRepository();
        TopBar topBar = null;

        
        protected override void Initialize(System.Web.Routing.RequestContext requestContext)
        {
            // no client input will be checked on any controllers
            ValidateRequest = false;
            base.Initialize(requestContext);

            InitialiseUser();
               
        }

        private void InitialiseUser()
        {
            // Grab the user's login information from FormsAuth
            //User userState = new User();
            if (this.User.Identity != null && this.User.Identity is FormsIdentity)
            {
                openID = ((FormsIdentity)this.User.Identity).Ticket.Name;

                int userID = UserHelper.GetUserIDFromIdentityTicket((FormsIdentity)this.User.Identity);
                string key = string.Format(Settings.Cache_User_ID_Key, userID);
                var userObject = WebCache.Get(key);

                if (Settings.CacheEnabled && userObject != null)
                {
                    // make user avaliable for all the controller
                    _user = (User)userObject;
                    ViewData["UserState"] = _user;
                }
                else
                {
                    // look up user by openid
                    _user = usersRepository.GetByOpenID(openID);
                  
                    if (_user == null)
                    {
                        // in case an user has been removed, but still autenticated
                        _user = new User();
                        topBar = new TopBar();
                        topBar.IsShow = true;
                        topBar.Message = "Sorry, user profile is not found in our system, please contact us.";

                        ViewData["topBar"] = topBar;
                    }
                    else
                    {
                        // update the login times and last login time
                        // create a new in the user controller section
                        _user.LoginTimes += 1;
                        _user.DateLastLogin = DateTime.Now;
                        usersRepository.Merge(_user);

                        // add cache
                        WebCache.Add(key, _user);

                        // have to explicitly add this so MasterPage can get untyped value
                        ViewData["UserState"] = _user;
                    }

                }
            }
        }

        /// <summary>
        /// Allow external initialization of this controller by explicitly
        /// passing in a request context
        /// </summary>
        /// <param name="requestContext"></param>
        public void InitializeForced(RequestContext requestContext)
        {
            this.Initialize(requestContext);
        }


    }
}
